package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.CourseConstants;
import cn.itsource.ymcc.constant.PayConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.Course;
import cn.itsource.ymcc.domain.CourseUserLearn;
import cn.itsource.ymcc.mapper.CourseMapper;
import cn.itsource.ymcc.mapper.CourseUserLearnMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "CoursePayConsumer",//消费者组名
        topic = PayConstants.TOPIC_PAY_COURSE_MESSAGE,
        selectorExpression = PayConstants.TAGS_PAY_COURSE_MESSAGE
)
public class CoursePayConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private CourseUserLearnMapper courseUserLearnMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            byte[] body = messageExt.getBody();
            String s = new String(body, Constants.UTF8);
            JSONObject jsonObject = JSON.parseObject(s);
            String courses = jsonObject.get("courses").toString();
            //分割
            String[] courseIds = courses.split(",");
            List<Course> courseList = courseMapper.selectBatchIds(Arrays.asList(courseIds));
            courseList.forEach(course -> {
                CourseUserLearn courseUserLearn = new CourseUserLearn();
                courseUserLearn.setCourseId(course.getId());
                courseUserLearn.setCourseOrderNo(jsonObject.get("orderNo").toString());
                courseUserLearn.setCreateTime(new Date());
                courseUserLearn.setStartTime(course.getStartTime());
                courseUserLearn.setEndTime(course.getEndTime());
                courseUserLearn.setLoginId(Long.valueOf(jsonObject.get("userId").toString()));
                courseUserLearn.setState(RConst.Num.INT_0);
                courseUserLearnMapper.insert(courseUserLearn);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
